const EventEmitter = require('events');
const util = require('util');

function Dog(name, energy) {
  EventEmitter.call(this);
  this.name = name;
  this.energy = energy;
  this._timer = null;
}

util.inherits(Dog, EventEmitter);

Dog.prototype.start = function start() {
  if (this._timer) return;
  const self = this;
  this._timer = setInterval(function tick() {
    if (self.energy > 0) {
      self.energy -= 1;
      self.emit('bark', self.name, self.energy);
      if (self.energy === 0) {
        clearInterval(self._timer);
        self._timer = null;
      }
    } else {
      clearInterval(self._timer);
      self._timer = null;
    }
  }, 1000);
};

module.exports = Dog;
